﻿using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Assets.Scripts.Game.ResourceConfig;
using UnityEditor;
using UnityEditor.UI;
using UnityEngine;
using LitJson;

using Debug = UnityEngine.Debug;

namespace Assets.Editor
{


    public class ResConfig
    {
        public  ResConfig()
        {
            l = new List<ResConfigInfo>();
        }

        public List<ResConfigInfo> l;
    }

    public class BuilderAsset : UnityEditor.Editor
    {
        public static string platform = string.Empty;
        static List<string> paths = new List<string>();
        static List<string> files = new List<string>();

        /// <summary>
        /// 载入素材
        /// </summary>
        static UnityEngine.Object LoadAsset(string file)
        {
            if (file.EndsWith(".lua")) file += ".txt";
            return AssetDatabase.LoadMainAssetAtPath("Assets/Builds/" + file);
        }

        /// <summary>
        /// 生成绑定素材
        /// </summary>
        [MenuItem("Game/Parse AssetBundles")]
        public static void BuildAllAssetResource()
        {
            /**
             u5 assetbundle使用了新的方法，所以需要重新处理所有meta文件，根据策划的配置，重新生成assetbundle文件
             */

            //读取文件的位置
            string configDataPath = Application.dataPath + "/Builds/Pub_Res_Config.json";

            var textObj = Resources.Load("Pub_Res_Config") as TextAsset;
           
            JsonData  jsonObj = JsonMapper.ToObject(textObj.text);
           ResConfig config = new ResConfig();
            

            for (int i = 0; i < jsonObj.Count; ++i)
            {
                ResConfigInfo t = new ResConfigInfo();
                t.assetbundle = (string)jsonObj[i]["assetbundle"];
                t.index_id = (int)jsonObj[i]["index_id"];
                t.prefab = (string)jsonObj[i]["prefab"];
                t.res = (string)jsonObj[i]["res"];
                t.res_path = (string)jsonObj[i]["res_path"];
                config.l.Add(t);
            }
          
            //根据对应的数据，开始打包数据
            string prefabSaveDataPath = Application.dataPath + "/Builds/Prefabs/";

            /**
             * 删除所有的prefab
             */
            if (Directory.Exists(prefabSaveDataPath))
            {
                Directory.Delete(prefabSaveDataPath, true);
            }
            Directory.CreateDirectory(prefabSaveDataPath);


            for (int i = 0; i < config.l.Count; ++i)
            {
                ResConfigInfo t = config.l[i];
                string prefabPath = prefabSaveDataPath + t.prefab + ".prefab";
                GameObject prefabObj;
                if (File.Exists(prefabPath))
                {
                    Debug.Log("prefab repeat:" + prefabPath + "index:" + t.index_id);                    
                }
                else
                {
                    //读取数据对象
                    string objPath = "Assets/" + t.res_path + t.res;
                    string prefabSavePath = "Assets" + "/Builds/Prefabs/" + t.prefab+".prefab";

                    GameObject tGameObject = (GameObject) AssetDatabase.LoadAssetAtPath(objPath, typeof (GameObject));

                    prefabObj = (GameObject)PrefabUtility.CreatePrefab(prefabSavePath, tGameObject);
                    if (prefabObj == null)
                    {
                        Debug.Log("create prefab fail:" + prefabSavePath);
                    }
                }
            }

            AssetDatabase.Refresh();
            for (int i = 0; i < config.l.Count; ++i)
            {
                ResConfigInfo t = config.l[i];
                string prefabPath = prefabSaveDataPath + t.prefab + ".prefab";
                
                if (File.Exists(prefabPath))
                {
                    string path = prefabPath + ".meta";

                    StreamReader sReader = new StreamReader(path);
                    List<string> ret = new List<string>();
                    string line;
                    while ((line = sReader.ReadLine()) != null)
                    {
                        line = line.Replace("\n", "");
                        if (line.IndexOf("assetBundleName:") != -1)
                        {
                            line = "  assetBundleName: " + t.assetbundle.ToLower() + ".unity3d";
                        }
                        ret.Add(line);
                    }
                    sReader.Close();

                    File.Delete(path);

                    StreamWriter writer = new StreamWriter(path + ".tmp");
                    foreach (var each in ret)
                    {
                        writer.WriteLine(each);
                    }
                    writer.Close();

                    File.Copy(path + ".tmp", path);
                    File.Delete(path + ".tmp");     
                }
                else
                {
                    Debug.Log("prefab no create:" + prefabPath + "index:" + t.index_id);                
                }
            }








            string assetfile = string.Empty;  //素材文件名
            string resPath = AppDataPath + "/" + Const.AssetDirname + "/";
            if (!Directory.Exists(resPath)) Directory.CreateDirectory(resPath);
            BuildPipeline.BuildAssetBundles(resPath, BuildAssetBundleOptions.None, BuildTarget.Android);



            string luaPath = resPath + "/lua/";

            //----------复制Lua文件----------------
            if (Directory.Exists(luaPath))
            {
                Directory.Delete(luaPath, true);
            }
            Directory.CreateDirectory(luaPath);

            paths.Clear(); files.Clear();
            string luaDataPath = Application.dataPath + "/lua/".ToLower();
            Recursive(luaDataPath);
            foreach (string f in files)
            {
                if (f.EndsWith(".meta")) continue;
                string newfile = f.Replace(luaDataPath, "");
                string newpath = luaPath + newfile;
                string path = Path.GetDirectoryName(newpath);
                if (!Directory.Exists(path)) Directory.CreateDirectory(path);
                File.Copy(f, newpath, true);
            }

            ///----------------------创建文件列表-----------------------
            string newFilePath = resPath + "/files.txt";
            if (File.Exists(newFilePath)) File.Delete(newFilePath);

            paths.Clear(); files.Clear();
            Recursive(resPath);

            FileStream fs = new FileStream(newFilePath, FileMode.CreateNew);
            StreamWriter sw = new StreamWriter(fs);
            for (int i = 0; i < files.Count; i++)
            {
                string file = files[i];
                string ext = Path.GetExtension(file);
                if (ext.Equals(".meta")) continue;

                string value = file.Replace(resPath, string.Empty);
                sw.WriteLine(value);
            }
            sw.Close(); fs.Close();
            AssetDatabase.Refresh();
        }

        /// <summary>
        /// 数据目录
        /// </summary>
        static string AppDataPath
        {
            get { return Application.dataPath.ToLower(); }
        }

        /// <summary>
        /// 遍历目录及其子目录
        /// </summary>
        static void Recursive(string path)
        {
            string[] names = Directory.GetFiles(path);
            string[] dirs = Directory.GetDirectories(path);
            foreach (string filename in names)
            {
                string ext = Path.GetExtension(filename);
                if (ext.Equals(".meta")) continue;
                files.Add(filename.Replace('\\', '/'));
            }
            foreach (string dir in dirs)
            {
                paths.Add(dir.Replace('\\', '/'));
                Recursive(dir);
            }
        }
    }
}